package com.youlai.mybatis.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;

import java.sql.Statement;
import java.util.Properties;

/**
 * @author zc
 * @date 2023-03-21 22:47
 */
@Intercepts({
        @Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class})
})
@Slf4j
public class MybatisPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // TODO: 拦截逻辑
        log.info("进入拦截器");
        long startTime = System.currentTimeMillis();
        Object result = invocation.proceed();
        long endTime = System.currentTimeMillis();
        long sqlTime = endTime - startTime;
        StatementHandler statementHandler = (StatementHandler)invocation.getTarget();
        String sql = statementHandler.getBoundSql().getSql();
        ParameterHandler parameterHandler = statementHandler.getParameterHandler();
        log.info("执行sql:{},参数:{},花费了{}毫秒",sql,parameterHandler.getParameterObject().toString(),sqlTime);
        return result;
    }

    @Override
    public Object plugin(Object target) {
        log.info("生成代理对象");
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
        log.info("设置插件属性");
        Interceptor.super.setProperties(properties);
    }
}

